package com.jiwen.controller;

import com.github.pagehelper.PageInfo;
import com.jiwen.dto.ApkDto;
import com.jiwen.pojo.AppInfo;
import com.jiwen.pojo.AppVersion;
import com.jiwen.service.AppCategoryService;
import com.jiwen.service.AppInfoService;
import com.jiwen.service.AppVersionService;
import com.jiwen.vo.CategoryVo;
import com.jiwen.vo.ResultVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author shrstart
 * @create 2023-12-16-10:46
 */

@RestController
@RequestMapping("/appInfo")
public class AppInfoController {

    @Autowired
    AppInfoService appInfoService;

    @Autowired
    AppCategoryService appCategoryService;

    @Autowired
    AppVersionService appVersionService;

    /*条件分页查询*/
    @RequestMapping("/selAppInfos")
    public ResultVo selAppInfos(@RequestBody AppInfo appInfo, Integer pageNum, HttpServletRequest request) {
        String token = request.getHeader("token");
        String[] split = token.split("-");

        if(split[3].equals("admin")){
            appInfo.setStatus(1L);
        }

        PageInfo<AppInfo> page = appInfoService.selAppInfos(appInfo, pageNum);

        return ResultVo.success("", page);
    }

    /*查询三级联动*/
    @RequestMapping("/selCategory")
    public ResultVo selCategory() {
        CategoryVo categoryVo = appCategoryService.selCategory();

        return ResultVo.success("", categoryVo);
    }

    /*验证APK唯一性*/
    @PostMapping("/apkType")
    public ResultVo apkType(@RequestBody ApkDto apkDto) {

        Long apkNum = appInfoService.selApkSum(apkDto.getApkName());


        if (apkNum > 0) {
            if (apkDto.getAppId() == null) {

                return ResultVo.error("APK名称不可用");

            } else {

                AppInfo appInfo = appInfoService.selAppInfo(apkDto.getAppId());

                if (appInfo.getApkname().equals(apkDto.getApkName())) {
                    return ResultVo.success("APK名称可用", null);
                } else {
                    return ResultVo.error("APK名称不可用");
                }

            }
        } else {
            return ResultVo.success("APK名称可用", null);
        }
    }

    /*新增、修改*/
    @PostMapping("/addOrUpdate")
    public ResultVo addOrUpdate(AppInfo appInfo, MultipartFile logoFile, HttpServletRequest request) {

        if (logoFile != null) {
            String filePath = request.getServletContext().getRealPath("/upload/images");
            File file = new File(filePath);

            if (!file.exists()) {
                file.mkdirs();
            }

            if (logoFile.getSize() > 1024 * 1024) {
                return ResultVo.error("图片不能超过1MB");
            } else {
                String fileName = logoFile.getOriginalFilename();
                String fileSuffix = FilenameUtils.getExtension(fileName);

                if (
                        fileSuffix.equalsIgnoreCase("jpg") ||
                                fileSuffix.equalsIgnoreCase("jpeg") ||
                                fileSuffix.equalsIgnoreCase("png") ||
                                fileSuffix.equalsIgnoreCase("gif")
                ) {
                    String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + fileSuffix;
                    File newFile = new File(filePath + "/" + newFileName);

                    try {
                        logoFile.transferTo(newFile);

                        appInfo.setLogopicpath("/upload/images/" + newFileName);
                        appInfo.setLogolocpath(filePath + "/" + newFileName);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    return ResultVo.error("图片格式错误");
                }
            }
        }

        StringBuffer message = new StringBuffer();

        if (appInfo.getId() == null) {
            message.append("新增");
        } else {
            message.append("修改");
        }

        Integer num = appInfoService.addOrUpdate(appInfo, request);


        if (num > 0) {
            return ResultVo.success(message.append("成功").toString(), null);
        } else {
            return ResultVo.error(message.append("失败").toString());
        }
    }

    /*查询单个APP信息*/
    @RequestMapping("/selAppInfo/{appId}")
    public ResultVo selAppInfo(@PathVariable Long appId) {

        AppInfo appInfo = appInfoService.selAppInfo(appId);

        return ResultVo.success("", appInfo);
    }

    /*删除APP信息*/
    @PostMapping("/delAppInfo/{appId}")
    public ResultVo delAppInfo(@PathVariable Long appId, HttpServletRequest request){
        AppInfo appInfo = appInfoService.selAppInfo(appId);

        File file = new File(appInfo.getLogolocpath());

        if(file.exists()){
            file.delete();
        }

        /*查询该APP的所有版本信息*/
        AppVersion appVersion = new AppVersion();
        appVersion.setAppid(appId);
        List<AppVersion> appVersions = appVersionService.selAppVersions(appVersion);

        for(AppVersion version : appVersions){
            file = new File(version.getApklocpath());

            if(file.exists()){
                file.delete();
            }
            /*删除改APP所有版本*/
            appVersionService.delVersion(version.getId());
        }

        Integer num = appInfoService.delAppInfo(appId);

        if(num > 0) {
            return ResultVo.success("删除成功", null);
        }else{
            return ResultVo.error("删除失败");
        }
    }

    /*修改APP状态*/
    @PostMapping("/audit")
    public ResultVo audit(@RequestBody AppInfo appInfo, HttpServletRequest request){

        StringBuffer message = new StringBuffer();
        if(appInfo.getStatus() == 2){
            message.append("审核");
        }else if(appInfo.getStatus() == 3){
            message.append("打回");
        }else if(appInfo.getStatus() == 4){
            message.append("上架");
        }else if(appInfo.getStatus() == 5){
            message.append("下架");
        }else{
            return ResultVo.error("非法操作");
        }

        Integer num =appInfoService.addOrUpdate(appInfo,request);

        if(num > 0){
            message.append("成功");
            return ResultVo.success(message.toString(),null);
        }else{
            message.append("失败");
            return ResultVo.error(message.toString());
        }

    }
}
